package com.strawberry.chat2.library.netease.p2p;

import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableArray;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeArray;
import com.facebook.react.bridge.WritableNativeMap;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.RequestCallbackWrapper;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.QueryDirectionEnum;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.strawberry.chat2.MyReactDelegate;
import com.strawberry.chat2.library.common.StoregeModule;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class P2PModule extends ReactContextBaseJavaModule {

    public P2PModule(ReactApplicationContext context) {
        super(context);
        Util.context = context;
    }

    @Override
    public String getName() {
        return "H5NeteaseP2P";
    }

    @ReactMethod
    public void login(String account, String token, final Callback errorCallback){
        LoginInfo info = new LoginInfo(account, token);
        final RequestCallback<LoginInfo> callback =
                new RequestCallback<LoginInfo>() {
                    @Override
                    public void onSuccess(LoginInfo param) {
                        //友盟账号登陆
                        MobclickAgent.onProfileSignIn(param.getAccount());
                        //注册响应消息
                        Util.onMessage();
                        //被踢出
                        Util.onLogout();
                    }

                    @Override
                    public void onFailed(int code) {
                        errorCallback.invoke();
                    }

                    @Override
                    public void onException(Throwable exception) {
                        errorCallback.invoke();
                    }
                    // 可以在此保存LoginInfo到本地，下次启动APP做自动登录用
                };
        NIMClient.getService(AuthService.class).login(info)
                .setCallback(callback);

        StoregeModule storegeModule = new StoregeModule(Util.context);
        storegeModule.setItem("account",account);
        storegeModule.setItem("netease_token",token);
    }

    @ReactMethod
    public void logout(){
        StoregeModule storegeModule = new StoregeModule(Util.context);
        String account = storegeModule.getItenAsync("account");
        storegeModule.removeItem("account");
        storegeModule.removeItem("netease_token");

        MobclickAgent.onProfileSignIn(account);
        NIMClient.getService(AuthService.class).logout();
        MyReactDelegate.isLogin = false;
        MyReactDelegate.account = "";
    }

    @ReactMethod
    public void sendTxtMsg(String fuid, String tuid, String content){
        // 该帐号为示例，请先注册
        String account = tuid;
        // 以单聊类型为例
        SessionTypeEnum sessionType = SessionTypeEnum.P2P;
        String text = content;
        // 创建一个文本消息
        IMMessage textMessage = MessageBuilder.createTextMessage(account, sessionType, text);
        textMessage.setFromAccount(fuid);
        textMessage.setMsgAck();
        // 发送给对方
        NIMClient.getService(MsgService.class).sendMessage(textMessage, false);
    }

    @ReactMethod
    public void getChatLog(String account, String etime, final Callback callback){
        // 以P2P类型为例，testAccount为测试帐号
        IMMessage msg = MessageBuilder.createEmptyMessage(account, SessionTypeEnum.P2P, Long.valueOf(etime));
        // 查询比 anchor时间更早的消息，查询20条，结果按照时间降序排列
        NIMClient.getService(MsgService.class).queryMessageListEx(msg, QueryDirectionEnum.QUERY_OLD,
                20, true).setCallback(new RequestCallbackWrapper<List<IMMessage>>() {
            @Override
            public void onResult(int code, List<IMMessage> result, Throwable exception) {
                WritableArray chatLogList = Util.extratMessage(result);
                callback.invoke(chatLogList);
            }
        });
    }

    @ReactMethod
    public void recentChats(final Callback callback){
        NIMClient.getService(MsgService.class).queryRecentContacts()
                .setCallback(new RequestCallbackWrapper<List<RecentContact>>() {
                    @Override
                    public void onResult(int code, List<RecentContact> recents, Throwable e) {
                        // recents参数即为最近联系人列表（最近会话列表）
                        WritableArray userList = new WritableNativeArray();

                        if(recents != null) {
                            List<String> uidList = new ArrayList<String>();
                            Map<String, String> contentMap = new HashMap<String, String>();
                            Map<String, String> timeMap = new HashMap<String, String>();
                            for( int i = 0 ; i < recents.size() ; i++) {//内部不锁定，效率最高，但在多线程要考虑并发操作的问题。
                                //好友用户ID
                                String uid = recents.get(i).getContactId();
                                uidList.add(uid);
                                String content = recents.get(i).getContent();
                                contentMap.put(uid, content);
                                Long time = recents.get(i).getTime();
                                timeMap.put(uid, String.valueOf(time));
                            }
                            List<NimUserInfo> users = NIMClient.getService(UserService.class).getUserInfoList(uidList);
                            if(users != null) {
                                for (int i = 0; i < users.size(); i++) {
                                    WritableMap user = new WritableNativeMap();
                                    String uid = users.get(i).getAccount();
                                    user.putString("uid", uid);
                                    user.putString("name", users.get(i).getName());
                                    user.putString("avatar", users.get(i).getAvatar());
                                    user.putString("content", contentMap.get(uid));
                                    user.putString("time", timeMap.get(uid));
                                    userList.pushMap(user);
                                }
                            }

                            //  创建观察者对象
//                            Observer<List<RecentContact>> messageObserver =
//                                    new Observer<List<RecentContact>>() {
//                                        @Override
//                                        public void onEvent(List<RecentContact> messages) {
//                                        }
//                                    };
//                            //  注册/注销观察者
//                            NIMClient.getService(MsgServiceObserve.class)
//                                    .observeRecentContact(messageObserver, true);
                        }
                        callback.invoke(userList);
                    }
                });
    }
}
